package com.atguigu.yygh.hosp.mongo;


import com.atguigu.yygh.common.result.Result;
import com.mongodb.client.result.DeleteResult;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/mongo1")
public class TestMongo1 {

    @Autowired
    private MongoTemplate mongoTemplate;


    @ApiOperation("添加")
    @PostMapping("/create")
    public Result createUser () {
        User u = new User();
        u.setAge(20);
        u.setName("test");
        u.setEmail("4932200@qq.com");
        User user = mongoTemplate.save(u);
        System.out.println("user = " + user);
        return Result.ok().data("user",user);
    }

    //查询全部
    @ApiOperation("查询全部")
    @GetMapping("/findAll")
    public Result findAll() {
        List<User> all = mongoTemplate.findAll(User.class);
        System.out.println("all = " + all);

        return Result.ok().data("all",all);
    }


    @ApiOperation("删除")
    @PostMapping("/delete/{id}")
    public Result delete(@PathVariable String id) {
        Query query = new Query(Criteria.where("_id").is("61b33784a14fac777f363d90"));
        DeleteResult result = mongoTemplate.remove(query, User.class);
        long count = result.getDeletedCount();
        System.out.println("count = " + count);
        return Result.ok();
    }

    @ApiOperation("根据id查询")
    @GetMapping("/findById")
    public Result findById() {
        User u = mongoTemplate.findById("61b3446390285399c0ecf127", User.class);
        System.out.println("u = " + u);
        return Result.ok().data("u",u);
    }

    @ApiOperation("条件查询")
    @GetMapping("/find")
    public Result find() {
        Query query = new Query(Criteria.where("name").is("zhangsi").and("age").is(35));
        List<User> users = mongoTemplate.find(query, User.class);
        System.out.println("users = " + users);
        return Result.ok().data("users",users);
    }
}
